package 链表与双指针.m03.d21.t04;

import 链表与双指针.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, cur = head;
        int count = 0;
        while (l1 != null || l2 != null) {
            int val1 = (l1 == null) ? 0 : l1.val;
            int val2 = (l2 == null) ? 0 : l2.val;
            int res = val1 + val2 + count;
            int last = res % 10;
            count = res / 10;
            if (head == null) {
                head = new ListNode();
                head.val = last;
                cur = head;
            } else {
                ListNode tmp = new ListNode(last, null);
                cur.next = tmp;
                cur = cur.next;
            }
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
        }
        if (count == 1) {
            cur.next = new ListNode(1);
        }
        return head;
    }
}